<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Scale a text to fit inside of an element</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
    </head>
    <body>
        <div style="margin: 3rem 0; padding: 0 0.5rem">
            <div id="headline">Hello World</div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                const measureWidth = function (text, font) {
                    // Create an element
                    const ele = document.createElement('div');

                    // Set styles
                    ele.style.position = 'absolute';
                    ele.style.visibility = 'hidden';
                    ele.style.whiteSpace = 'nowrap';
                    ele.style.left = '-9999px';

                    // Set font and text
                    ele.style.font = font;
                    ele.innerText = text;

                    // Append to the body
                    document.body.appendChild(ele);

                    // Get the width
                    const width = window.getComputedStyle(ele).width;

                    // Remove the element
                    document.body.removeChild(ele);

                    return width;
                };

                // Query the element
                const ele = document.getElementById('headline');

                // Get the styles
                const styles = window.getComputedStyle(ele);

                // Get the font size and font style
                const font = styles.font;
                const fontSize = parseInt(styles.fontSize);

                // Calculate the scale
                const measured = measureWidth(ele.textContent, font);
                const scale = ele.clientWidth / parseFloat(measured);

                const scaleFontSize = Math.floor(scale * fontSize);
                ele.style.fontSize = `${scaleFontSize}px`;
            });
        </script>
    </body>
</html>
